package com.tina.handle;


import com.tina.exception.SysException;
import com.tina.utils.ResultFormat;
import com.tina.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.util.Locale;

/**
 * @author Tina
 * @since 2020-07-01
 * 异常返回
 */
@ControllerAdvice
public class ExceptionHandle {
    private static int DUPLICATE_KEY_CODE = -1;
    private static int PARAM_FAIL_CODE = 1002;
    private static int VALIDATION_CODE = 1003;


    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);


    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultFormat handle(Exception e) {
        if (e instanceof SysException) {
            SysException sysException = (SysException) e;
            return ResultUtil.error(sysException.getCode(), sysException.getMessage());
        } else {
            logger.error("【系统异常】{}", e);
            return ResultUtil.error(-1, "未知错误");
        }
    }


    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultFormat handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        return ResultUtil.error(PARAM_FAIL_CODE, e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public ResultFormat handleValidationException(ValidationException e) {
        logger.error(e.getMessage(), e);
        return ResultUtil.error(VALIDATION_CODE, e.getCause().getMessage());
    }

    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultFormat handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage(), e);
        return ResultUtil.error(PARAM_FAIL_CODE, e.getMessage());
    }
}
